<?php
namespace app\admin\controller;

use thinkless\common\AdminController;
use exception\FriendlyException;
use app\admin\model\AdminModel;
use app\admin\service\AdminService;
use ui\Form;
use util\PasswordHash;
use ui\Button;
use ui\FormField;
use ui\Icon;
use ui\Table;
use ui\TableColumn;
use ui\MessageBox;

class Admin extends AdminController {

    /**
     * 首页
     */
    public function index() {
        function buildForm($title, $url) {
            return Form::createDialogBuilder($title, ['width' => 720, 'top' => '20px', 'maxHeight' => '70vh'])
                ->addCancleButton()
                ->addConfirmButton($url)
                ->addField(FormField::createInput('username', '用户名')->setRequired())
                ->addField(FormField::createInput('mobile', '手机号')->setRequired());
        }
        $createForm = buildForm('新增管理员', '/admin/admin/create');
        $editForm = buildForm('编辑管理员', '/admin/admin/edit');
        $table = Table::create()
            ->withQueryUrl('/admin/admin/list')
            ->addButton(Button::create('create', $createForm)->setLabel('新增管理员')->setIcon(Icon::ADD))
            ->addSearch(FormField::createInput('id', 'ID'))
            ->addSearch(FormField::createSelect('status', '状态', AdminModel::getUIOptions('status')))
            ->addSearch(FormField::createInput('username', '用户名'))
            ->addColumn(TableColumn::create('id', 'ID'))
            ->addColumn(TableColumn::create('status_name', '状态'))
            ->addColumn(TableColumn::create('username', '用户名'))
            ->addColumn(TableColumn::create('mobile', '手机号'))
            ->addColumn(TableColumn::create('last_login_time', '最后登录时间'))
            ->addColumn(TableColumn::create('action', '操作')->setMinWidth(80)
                    ->addButton(Button::create('edit', $editForm)->setLabel('编辑'))
                    ->addButton(Button::createDanger('del', MessageBox::createConfirm()->setMethodPost('/admin/admin/del')->setContent('确认删除管理员'))->setLabel('删除'))
                )
            ->buildJson();
        return $this->view('', ['table' => $table]);
    }

    public function list() {
        $list = (new AdminModel())->order('id desc')
            ->when(!empty(input('id')), ['id' => input('id')])
            ->when(!empty(input('username')), [['username', 'like', '%'.input('username').'%']])
            ->when(!empty(input('mobile')), [['mobile', 'like', '%'.input('mobile').'%']])
            ->when(!empty(input('status')), ['status' => input('status')])
            ->paginate($this->getPageSize());
        foreach ($list as $item) {
            $item->outputFormat($item);
            $item['actions'] = [
                'edit' => true,
                'del' => true,
            ];
        }
        return $this->jSuccess($list);
    }

    public function create() {
        $data = input('post.');
        if(empty($data['username'])) throw new FriendlyException("用户名必填");
        if(empty($data['mobile'])) throw new FriendlyException("手机号必填");
        if((new AdminModel)->hasByKey('username', $data['username'])) throw new FriendlyException("用户名已存在");
        // 创建用户
        $salt = PasswordHash::createSalt($data['mobile']);
        $encryptPassword = PasswordHash::encrypt_password('123456', $salt);
        $res = (new AdminModel)->create([
            'mobile' =>  $data['mobile'],
            'password' =>  $encryptPassword,
            'salt' =>  $salt,
            'status' => AdminModel::STATUS_NORMAL,
            'username' =>  $data['username'],
            'avatar_url' => '/image/avatar.jpg',
        ]);
        return $this->jSuccess($res);
    }

    public function edit() {
        $data = input('post.');
        $admin = (new AdminModel())->mustFindOne($data['id']);
        $newData = [];
        if(!empty($data['username']) && $admin['username'] != $data['username']) {
            if((new AdminModel)->hasByKey('username', $data['username'])) throw new FriendlyException("用户名已存在");
            $newData['username'] = $data['username'];
        }
        if(!empty($data['mobile'])) $newData['mobile'] = $data['mobile'];
        $admin->save($newData);
        return $this->jSuccess();
    }

    public function del() {
        $id = input('post.id');
        $admin = (new AdminModel())->mustFindOne($id);
        if($admin['is_super'] == 1) throw new FriendlyException("不能删除超级管理员");
        $admin->delete();
        return $this->jSuccess();
    }

    /**
     * 管理员重置密码
     */
    public function resetPassword() {
        $id = input('post.id');
        (new AdminService())->updatePassword($id, '123456');
        return $this->jSuccess();
    }
}
